import json
from datetime import datetime

from django.http import HttpResponse
from django.shortcuts import render, redirect


# Create your views here.
# 导入视图函数
from django.urls import reverse
from django.utils.decorators import method_decorator
from django.views import View


def index(resquest):

    return HttpResponse("hello world......")


def brouth(resquest):

    # 重定向  指向 brouter里的函数
    return redirect(reverse('parment:child'))


def parameter(request, year, city):
    # 请求对象的其他属性
    print(request.encoding)
    print(request.path)
    print(request.user)
    print(request.method)

    # 1.路径传参
    print('城市名字',city)
    print('年份',year)

    # 2.查询参数
    # request.GET ---> QuertDict:可以一键多值
    # params = request.GET
    #
    # print(params)  # <QueryDict: {'a': ['10', '30'], 'b': ['20']}>
    # print(params.get('b'))   # 20
    # print(params.get('a'))   # 30   当a有多值时，使用get方法只能获取到最后一个值
    # print(params.getlist('a'))   # ['10', '30'] 使用getlist会得到由a的所有值组成的一个列表

    # 3.请求体传参
    # 3.1 请求体参数--form参数
    # data = request.POST
    # print("-----")
    # print(data)  # <QueryDict: {'a': ['10', '30'], 'b': ['20']}>
    # print(data.getlist('a'))  # ['10', '30']
    # print(data.get('b')) # '20'

    # 3.2 请求体参数 -- 非form参数--json
    # request.body --> 得到的数据类型为bytes
    bytes_data = request.body
    print(bytes_data)  #  b'{\n    "name":"baoke",\n    "age":22,\n    "c":"1111111"\n    \n}'
    print(bytes_data.decode())
    '''
    以下为上一行代码输出结果
    {
    "name":"baoke",
    "age":22,
    "c":"1111111"
     }
    '''
    # 将json格式转换为列表或字典格式  loads
    # 将列表或字典转换为json格式  dumps
    print(json.loads(bytes_data.decode()))    # {'name': 'baoke', 'c': '1111111', 'age': 22}
    print(type(json.loads(bytes_data.decode())))   #  <class 'dict'>

    # 4.解析请求头   request.META --> dict
    headers = request.META
    print(headers)
    print(type(headers))  # <class 'dict'>
    print(headers.get("HTTP_NAME"))  # <class 'dict'>

    return HttpResponse("路径参数 解析")


# 定义一个装饰器
def my_decorator(func):
    def wrapper(request, **kwargs):
        print('自定义装饰器被调用了...')
        print(request.path)
        return func(request, **kwargs)
    return wrapper


# 定义类视图
# 给类视图添加装饰器方法二：在类视图中装饰
# name参数为必填项，dispatch是一个底层函数，派遣分发
# @method_decorator(my_decorator, name='dispatch')
# # 也可以单独为类视图中的某个函数装饰
# # @method_decorator(my_decorator, name='get')
# class RegisterView(View):
#     '''类视图：处理注册'''
#
#     def get(self,request):
#         print('get.......')
#         return HttpResponse('使用get方法')
#
#     # 也可以直接在函数头顶装饰
#     # @method_decorator(my_decorator)
#     def post(self,request):
#         print('post......')
#         return HttpResponse('使用post方法')


# 给类视图添加装饰器方法三：类视图Mixin扩展类
class MyDecoratorMixin(object):
    @classmethod
    def as_view(cls, *args, **kwargs):
        view = super().as_view(*args, **kwargs)
        view = my_decorator(view)
        return view

class DemoView(MyDecoratorMixin,View):
    def get(self, request):
        print('get方法')
        return HttpResponse('ok...111')

    def post(self, request):
        print('post方法')
        return HttpResponse('ok...222')


def demo_view(request):
    print('view 视图被调用')
    return HttpResponse('OK')

class TemplateView(View):
    def get(self,request):
        context = {
            'city': '北京',
            'age':18,
            'adict': {
                'name': '西游记',
                'author': '吴承恩'
            },
            'alist': [1, 2, 3, 4, 5],
            'today_date': datetime.now(),
            'safe_data': '<a href="#"> 传智的链接地址</a>'

        }
        # return render(request,'index.html',context=context)
        return render(request,'jinja2_index.html',context=context)


